package com.house.controller;

import com.house.code.Code;
import com.house.entity.*;
import com.house.mapper.HouseImageMapper;
import com.house.service.*;
import com.house.util.MD5Utils;
import com.house.util.PhoneCode;
import com.house.vo.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@RestController
//@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private HouseService houseService;
    @Autowired
    private CollectService collectService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private HouseImageMapper houseImageMapper;


    @RequestMapping("/register")
    public ModelAndView registerPage(){

        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("regist");

        return modelAndView;
    }
    @RequestMapping("/login")
    public ModelAndView loginPage(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("login");
        return mv;
    }

    @RequestMapping("/forget")
    public ModelAndView forgetPage(){
        ModelAndView mv=new ModelAndView("forget");
        return mv;
    }

    @PostMapping("/doforget")
    @ResponseBody
    public JsonVo doforget(@RequestParam("email")String email,@RequestParam("telphone")String telphone){
        JsonVo jsonVo = new JsonVo();
        try {
        UserLogin userLogin= userService.getByEmailorTelphone(email,telphone);

            if(userService.sendforgetEmail(userLogin)){
                jsonVo.setCode(200);
                jsonVo.setData("OK");
            }else {
                jsonVo.setCode(500);
                jsonVo.setData("OK");
            }
        }catch (Exception e){
            jsonVo.setCode(500);
            jsonVo.setData(e.toString());
        }


        return jsonVo;
    }



    @RequestMapping(value = "/dologin",method = RequestMethod.GET)
    private ModelAndView login(Authentication auth, HttpSession session, HttpServletResponse response) throws IOException {
        UserLogin userLogin = userService.findByAdmin(auth.getName());
        UserInf userInf=userService.findByUserLoginId(userLogin.getId());
        session.setAttribute("userLogin",userLogin);
        session.setAttribute("userInf",userInf);
        response.sendRedirect("house/houselist");
        return null;
    }


    @RequestMapping("/doregister")
    @ResponseBody
    private JsonVo register(@RequestParam("username")String admin,
                            @RequestParam("password")String password, @RequestParam("email")String email, @RequestParam("telphone")String telphone,  @RequestParam("nickname")String name,HttpSession session){

        JsonVo jsonVo=new JsonVo();
        UserLogin realUser=new UserLogin();
        realUser.setAdmin(admin);
        realUser.setEmail(email);
        realUser.setPassword(MD5Utils.md5(password));
        realUser.setTelphone(telphone);
        realUser.setUsertype(0);
        userService.addUserLogin(realUser,name);
        jsonVo.setCode(400);
        jsonVo.setData("注册成功");
       return jsonVo;

    }


    @RequestMapping(value = "/getCode",method = RequestMethod.POST)
    @ResponseBody
    public CodeVo getCode(@RequestParam("telphone") String telphone, HttpSession session){
        String random=String.format("%04d",new Random().nextInt(9999));
        //System.out.println(telphone);
        //System.out.println(telphone.length());
        CodeVo codeVo=new CodeVo();
        if (telphone!=null&&!telphone.equals("")&&telphone.length()==11){
            try {
                PhoneCode.sendMsgByTxPlatform(telphone,random);
                session.setAttribute("code",random);
                session.setAttribute("telphone",telphone);
                codeVo.setCode(Code.CODE_SUCCESS);
                codeVo.setData("验证码发送成功");
                return codeVo;
            } catch (Exception e) {
                //System.out.println(111);
                e.printStackTrace();
            }
        }else {
            codeVo.setCode(Code.TELPHONE_ERROR);
            codeVo.setData("手机号格式错误");
            return codeVo;
        }
        codeVo.setCode(Code.SYSTEM_ERROR);
        codeVo.setData("系统未知错误");
        return codeVo;
//        PhoneCode.sendMsgByTxPlatform();
    }

    @GetMapping("/user/mine")
    public ModelAndView mine(HttpSession session){
        UserInf userInf= (UserInf) session.getAttribute("userInf");
        UserLogin userLogin = (UserLogin)session.getAttribute("userLogin");
        ModelAndView modelAndView=new ModelAndView();

        modelAndView.addObject("userInf",userInf);
        modelAndView.addObject("user",userLogin);
        modelAndView.setViewName("my/mine");
        return modelAndView;
    }

    @RequestMapping("/user/myhouse")
    public ModelAndView myHouse(HttpSession session){
        ModelAndView modelAndView = new ModelAndView();

        if (session.getAttribute("userInf")!=null) {
            UserLogin userLogin = (UserLogin)session.getAttribute("userLogin");
            UserInf userInf = (UserInf) session.getAttribute("userInf");
            modelAndView.addObject("user",userLogin);
            modelAndView.addObject("userInf",userInf);
            List<House> houseList = houseService.findAllByUserId(userInf.getUserLoginId());
            modelAndView.addObject("houseList", houseList);
            modelAndView.setViewName("my/myhouse");
        }
        return modelAndView;
    }

    @RequestMapping("/user/center")
    public ModelAndView mypage(){
        ModelAndView modelAndView=new ModelAndView();


        modelAndView.setViewName("");
        return modelAndView;
    }

    @RequestMapping(value = "/user/mine",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView updateMine(@RequestParam("telphone")String telphone,@RequestParam("password") String password,@RequestParam("email") String email,@RequestParam("name")String name,@RequestParam("sex")String sex,HttpSession httpSession){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("my/mine");
        if (httpSession.getAttribute("userInf")!=null){
            UserInf userInf= (UserInf) httpSession.getAttribute("userInf");
            UserLogin userLogin = (UserLogin)httpSession.getAttribute("userLogin");
            userInf.setName(name);
            userInf.setSex(sex);
            userLogin.setEmail(email);
            userLogin.setTelphone(telphone);
            userLogin.setPassword(MD5Utils.md5(password));
            userService.updateUserLogin(userLogin);
            userService.updateInf(userInf);
            modelAndView.addObject("user",userLogin);
            modelAndView.addObject("userInf",userInf);
        }

        return modelAndView;
    }

    @RequestMapping("/user/collect")
    public ModelAndView collect(HttpSession httpSession){
        ModelAndView modelAndView=new ModelAndView();
        if (httpSession.getAttribute("userInf")!=null){
            UserLogin userLogin = (UserLogin)httpSession.getAttribute("userLogin");
            modelAndView.addObject("user",userLogin);
            UserInf userInf= (UserInf) httpSession.getAttribute("userInf");
            modelAndView.addObject("userInf",userInf);
            List<Collect> collectList=collectService.findAllByUserId(userInf.getUserLoginId());
            List<House> list=new ArrayList<>();
            for (Collect c:collectList
                 ) {
                House house=houseService.getById(c.getHouseId());
                list.add(house);
            }

            modelAndView.addObject("houseList",list);
        }

        modelAndView.setViewName("my/collect");
        return modelAndView;
    }

    @RequestMapping("/user/news")
    public ModelAndView news(HttpSession httpSession){
        ModelAndView modelAndView=new ModelAndView();
        if (httpSession.getAttribute("userInf")!=null){
            UserLogin userLogin = (UserLogin)httpSession.getAttribute("userLogin");
            modelAndView.addObject("user",userLogin);
            UserInf userInf= (UserInf) httpSession.getAttribute("userInf");
            modelAndView.addObject("userInf",userInf);
           List<House> houseList=houseService.findAllByUserId(userInf.getUserLoginId());
           List<NewsVo> newsVoList=new ArrayList<>();
            for (House house:houseList
                 ) {

                List<News> newsList=newsService.findAllByHouseId(house.getId());
                for (News news:newsList
                     ) {
                    NewsVo newsVo=new NewsVo();
                    newsVo.setHouseId(house.getId());
                    newsVo.setHouseImage(house.getMainImage());
                    newsVo.setHouseTitle(house.getTitle());
                    newsVo.setInf(news.getInf());
                    newsVo.setTelphone(news.getTelphone());
                    newsVo.setPrice(news.getPrice());
                    newsVo.setId(news.getId());
                    newsVo.setStatus(house.getStatus());
                    newsVoList.add(newsVo);
                }
            }
            modelAndView.addObject("newsVoList",newsVoList);

        }

        modelAndView.setViewName("my/news");
        return modelAndView;
    }

    @RequestMapping("/user/message")
    public ModelAndView modelAndView(HttpSession session){
        ModelAndView modelAndView=new ModelAndView();
        if (session.getAttribute("userInf")!=null){
            UserLogin userLogin = (UserLogin)session.getAttribute("userLogin");
            modelAndView.addObject("user",userLogin);
            UserInf userInf= (UserInf) session.getAttribute("userInf");
            modelAndView.addObject("userInf",userInf);
            List<Message> messageList=messageService.findAllByToUserId(userInf.getUserLoginId());
            List<MessageVo> messageVoList=new ArrayList<>();
            for (Message message:messageList
                 ) {
                MessageVo messageVo=new MessageVo();
                messageVo.setId(message.getId());
                messageVo.setContent(message.getContent());
                messageVo.setToUserId(userInf.getUserLoginId());
                UserInf sendUserInf=userService.findByUserLoginId(message.getUserId());
                messageVo.setUserId(message.getUserId());
                messageVo.setUserName(sendUserInf.getName());
                messageVo.setUserImageUrl(sendUserInf.getProfill());
                messageVoList.add(messageVo);
            }

            modelAndView.addObject("messageVoList",messageVoList);
        }

        modelAndView.setViewName("my/message");

        return modelAndView;
    }

    @RequestMapping(value = "/user/message/delete",method = RequestMethod.POST)
    @ResponseBody
    public JsonVo deleteMessage(@RequestParam("id")int id){
        //System.out.println(id);
        JsonVo jsonVo=new JsonVo();

        messageService.deleteById(id);
        return jsonVo;
    }




    @RequestMapping(value = "user/liuyan")
    public ModelAndView liuyan(HttpSession session,@RequestParam(value = "userId",defaultValue = "-1")int userId){
        System.out.println(userId);
        ModelAndView modelAndView=new ModelAndView();
        List<MessageVo> messageVoList = new ArrayList<>();
        List<Message> messagesList;
        modelAndView.addObject("isChat",true);
        UserInf userInf= (UserInf) session.getAttribute("userInf");
        if (userInf==null){
            modelAndView.setViewName("redirect:/login");
        }
        //若指定会话人，留言列表显示发表并只显示与此人的会话
        if(userId==-1){
            modelAndView.addObject("isChat",false);
            messagesList=messageService.findAllByToUserId(userInf.getUserLoginId());
        }else {
            modelAndView.addObject("toUserId",userId);
            messagesList=messageService.findByToUserIdAndUserId(userId,userInf.getUserLoginId());
            messagesList.addAll(messageService.findByToUserIdAndUserId(userInf.getUserLoginId(),userId));
        }
        Collections.sort(messagesList, new Comparator<Message>() {

            @Override
            public int compare(Message o1, Message o2) {
                int flag = o2.getCreateTime().compareTo(o1.getCreateTime());
                return flag;
            }
        });
        for(Message message:messagesList){
            UserLogin fromuser = userService.findByid(message.getUserId());
            UserInf fromuserinfo = userService.findByUserLoginId(fromuser.getId());
            MessageVo messageVo = new MessageVo();
            messageVo.setId(message.getId());
            messageVo.setUserId(fromuser.getId());
            messageVo.setUserImageUrl(fromuserinfo.getProfill());
            messageVo.setContent(message.getContent());
            messageVo.setToUserId(message.getToUserId());
            messageVo.setCreateDate(message.getCreateTime());
            messageVo.setUserName(String.format("%s（%s）", fromuserinfo.getName(),fromuser.getAdmin()));
            messageVoList.add(messageVo);
        }
        modelAndView.addObject("toUserId",userId);
        modelAndView.addObject("messagesList",messageVoList);
        modelAndView.addObject("userInf",userInf);

        modelAndView.setViewName("my/liuyan");
        return modelAndView;
    }
    @RequestMapping(value = "/doLiuYan",method = RequestMethod.POST)
    @ResponseBody
    public JsonVo doLiuYan(@RequestParam("toUserId")int toUserId,@RequestParam("content")String content,HttpSession httpSession){
        JsonVo jsonVo=new JsonVo();
        UserInf userInf= (UserInf) httpSession.getAttribute("userInf");
        if (userInf!=null){
            messageService.insertOne(userInf.getUserLoginId(),toUserId,content);
        }
        return jsonVo;
    }
    @RequestMapping(value = "/agreeNews",method = RequestMethod.POST)
    @ResponseBody
    public JsonVo agreeNews(@RequestParam("id")int id,HttpSession httpSession){
        JsonVo jsonVo=new JsonVo();
        UserInf userInf= (UserInf) httpSession.getAttribute("userInf");
        if (userInf!=null){
            News news=newsService.findById(id);
            House house=houseService.getById(news.getHouseId());
            house.setStatus(2);
            houseService.updateById(house);
            System.out.println(house.getStatus());
            List<News> newsList = newsService.findAllByHouseId(news.getHouseId());
            for(News news1:newsList){
                if(news.getId()==news1.getId()){
                    messageService.insertOne(userInf.getUserLoginId(),news1.getUserId(),"我已经同意了你的合租请求！");
                }else {
                    messageService.insertOne(userInf.getUserLoginId(),news1.getUserId(),"我已经拒绝了你的合租请求！");
                    newsService.deleteById(news1.getId());
                }
            }

        }
        return jsonVo;
    }

    @RequestMapping(value = "/deleteNews",method = RequestMethod.POST)
    @ResponseBody
    public JsonVo deleteNews(@RequestParam("id")int id,HttpSession httpSession){
        JsonVo jsonVo=new JsonVo();
        UserInf userInf= (UserInf) httpSession.getAttribute("userInf");
        if (userInf!=null){
            News news=newsService.findById(id);
            messageService.insertOne(userInf.getUserLoginId(),news.getUserId(),"我已经拒绝了你的合租请求！");
            newsService.deleteById(id);

        }
        return jsonVo;
    }


}
